<template>
  <div class="app-container" v-if="noshowForm">
    <div class="query-wrapper" style="margin-bottom: 20px;" model="queryParams">
      <el-input v-model="queryParams.fixtureCode" style="width: 220px" placeholder="Fixture Code" clearable/> &nbsp;&nbsp;  
      <el-select
        v-model="queryParams.vesselName"
        filterable
        clearable
        placeholder="Vessel"
        style="width:180px"
        @change="selectVessel"
      >
        <el-option :key="item.vesselName" :label="item.vesselName" :value="item.vesselName" v-for="item in vessels">
        </el-option>
      </el-select> 
      &nbsp;&nbsp;
      <el-select v-model="queryParams.voyageNo" filterable clearable placeholder="Voyage" @change="selectVoyage"  style="width:100px">
        <el-option :key="item.voyageNo" :label="item.voyageNo" :value="item.voyageNo" v-for="item in voyages">
        </el-option>
      </el-select> 
      &nbsp;&nbsp;
      <el-select v-model="queryParams.pol" filterable clearable placeholder="POL">
          <el-option :key="item.portName" :label="item.portName" :value="item.portName" v-for="item in pols">
          </el-option>
    </el-select>
        &nbsp;&nbsp;
      <el-select v-model="queryParams.pod" filterable clearable placeholder="POD">
        <el-option :key="item.portName" :label="item.portName" :value="item.portName" v-for="item in pods">
        </el-option>
      </el-select>  
      &nbsp;&nbsp;
      <el-select v-model="queryParams.clientName" filterable clearable allow-create placeholder="Charterer">
        <el-option :key="item.fullName" :label="item.fullName" :value="item.fullName" v-for="item in clients">
        </el-option>
      </el-select>      
      <span>&nbsp;&nbsp;</span> 
      <el-button type="primary" icon="search" @click="search">{{ $t("ship.button.search") }}</el-button>
      <SearchReset :query-params="queryParams" @reset="resetQuery"></SearchReset>
      <span>&nbsp;&nbsp;</span> 
      <el-button type="primary" plain icon="plus" v-hasPermi="['freightConfirm:add']" @click="addClickEvent">
        Add
      </el-button>  
    </div>
 
   <el-table stripe :border="true" ref="tableRef" :data="listData" style="width: 100%" @sort-change="handleSortChange" show-overflow-tooltip> 
     <el-table-column prop="fixtureCode" label="Fixture Code" width="170" align="center" sortable="custom" :sort-orders="['descending', 'ascending']" />
     <el-table-column prop="freightDate" label="Date" width="100" align="center" sortable="custom" :sort-orders="['descending', 'ascending']" />  
     <el-table-column prop="salesMan" label="Prepared By" width="100"  align="center" sortable="custom" :sort-orders="['descending', 'ascending']" />
     <el-table-column prop="clientName" label="client" width="200"  align="center" sortable="custom" :sort-orders="['descending', 'ascending']" />
     <el-table-column prop="mobile" label="Mobile" width="100" align="center" sortable="custom" :sort-orders="['descending', 'ascending']" />
     <el-table-column prop="contact" label="Contact" width="150" align="center" sortable="custom" :sort-orders="['descending', 'ascending']" />
     <el-table-column prop="vesselName" label="Vessel Name" width="150" align="center" sortable="custom" :sort-orders="['descending', 'ascending']" />
     <el-table-column prop="voyageNo" label="Voyage"  align="center" sortable="custom" :sort-orders="['descending', 'ascending']" />
     <el-table-column prop="sailedOn" label="Sailed On" width="100" align="center" sortable="custom" :sort-orders="['descending', 'ascending']" />  
     <el-table-column prop="pod" label="POD"  width="140"  align="center" sortable="custom" :sort-orders="['descending', 'ascending']" />  
     <el-table-column prop="bookingNo" label="Booking No."  width="200" align="center" sortable="custom" :sort-orders="['descending', 'ascending']" />  
     <el-table-column prop="blNo" label="HB/L"  width="200" align="center" sortable="custom" :sort-orders="['descending', 'ascending']" /> 
     <el-table-column prop="units" label="Units"  align="center" sortable="custom" :sort-orders="['descending', 'ascending']" /> 
     <el-table-column prop="createBy" label="Created By"  width="120" sortable="custom" :sort-orders="['descending', 'ascending']" />
     <el-table-column label="Operation"  width="160" fixed="right">
       <template #default="scope">
         <span class="btn-primary" v-hasPermi="['freightConfirm:edit']"  @click="editClickEvent(scope.row)">{{ $t("ship.button.edit") }}</span
         >&nbsp;&nbsp;
         <span class="btn-primary" v-hasPermi="['freightConfirm:remove']"  @click="removeClickEvent(scope.row.id)">{{ $t("ship.button.remove") }}</span>
         &nbsp;&nbsp;
         <span class="btn-primary" v-hasPermi="['freightConfirm:export']"  @click="handleExport(scope.row)">{{ $t("ship.button.export") }}</span>
         &nbsp;&nbsp;
       </template>
     </el-table-column>
   </el-table>
 
   <pagination
     v-show="total > 0"
     :total="total"
     :page="queryParams.pageNum"
     :limit="queryParams.pageSize"
     @pagination="pageQuery"
     style="float: right"
   />
  </div>
   <div class="add-container" v-else>
    <el-form :model="formParam" :rules="rules" ref="custForm">
       <el-row>
         <el-col :span="8">
           <el-form-item label="Fixture Code" label-width="120px" prop="fixtureCode" required>
            <el-select v-model="formParam.fixtureCode" @change="selectFixture">
               <el-option v-for="item in fixtureNotes"
               :key = "item.fixtureNo"
               :value = "item.fixtureNo"
               :label="item.fixtureNo"
                />
             </el-select>
           </el-form-item>
         </el-col>
         <el-col :span="8">
           <el-form-item label="Date" label-width="120px" prop="freightDate" required>
            <el-date-picker value-format="YYYY-MM-DD" v-model="formParam.freightDate" class="ipt"
            placeholder="Please input" />
           </el-form-item>
         </el-col>
         <el-col :span="8">
           <el-form-item label="Prepared By" label-width="120px" prop="salesId"  >
            {{ user.username }}
           </el-form-item>
         </el-col>
       </el-row>
       <el-row>
        <el-col :span="8">
           <el-form-item  label="Client"  label-width="120px" prop="clientName" required>
            <el-input v-model="formParam.clientName" class="ipt" placeholder="Client Name" />
           </el-form-item>
         </el-col>
         <el-col :span="8">
           <el-form-item  label="Mobile" label-width="120px" prop="mobile" required>
            <el-input v-model="formParam.mobile" class="ipt" placeholder="Mobile" />
           </el-form-item>
         </el-col>
         <el-col :span="8">
           <el-form-item label="Contact"  label-width="120px" prop="contact" required>
            <el-input v-model="formParam.contact" class="ipt" placeholder="Contact" style="width:220px"/>			
           </el-form-item>
         </el-col>
       </el-row>
       <el-row>
        <el-col :span="8">
           <el-form-item  label="Vessel Name" label-width="120px" prop="vesselName" required>
            <el-input v-model="formParam.vesselName" class="ipt" placeholder="Vessel Name" />
           </el-form-item>
         </el-col>
         <el-col :span="8">
           <el-form-item label="Voyage"  label-width="120px" prop="voyageNo" required>
            <el-input v-model="formParam.voyageNo" class="ipt" placeholder="Voyage" />
           </el-form-item>
         </el-col>
         <el-col :span="8">
           <el-form-item  label="Sailed On" label-width="120px" prop="sailedOn" required>
            <el-date-picker value-format="YYYY-MM-DD"  v-model="formParam.sailedOn"/> 
           </el-form-item>
         </el-col>
       </el-row>
     <el-row> 
       <el-col :span="8">
           <el-form-item  label="POL" label-width="120px" prop="pol" required>
            <el-input type="textarea"  v-model="formParam.pol" rows="3"  placeholder="POL" />
           </el-form-item>
       </el-col>
       <el-col :span="8">
           <el-form-item  label="Booking No" label-width="120px" prop="bookingNo" required>
            <el-input type="textarea" v-model="formParam.bookingNo" rows="3"  placeholder="Booking No" />
           </el-form-item>
         </el-col>
         <el-col :span="8">
           <el-form-item label="B/L No."  label-width="120px" prop="blNo">
            <el-input v-model="formParam.blNo"  type="textarea" rows="3"  placeholder=" blNo" style="width:400px"/>
           </el-form-item>
         </el-col>
	   </el-row>
       <el-row> 
        <el-col :span="8">
           <el-form-item  label="POD" label-width="120px" prop="pod" required>
            <el-input type="textarea"  v-model="formParam.pod" rows="3" placeholder="POD" />
           </el-form-item>
        </el-col>
       </el-row> 
        <el-table :data="formParam.details" :rules="detailRules" stripe>
          <el-table-column label="Item" prop="item" width="100"/> 
          <el-table-column label="Fee Name" prop="feeName">
            <template #default="scope"> 
              <el-form-item  :prop="'details.'+scope.$index+'.feeName'" :rules="detailRules.feeName" required>
                <el-input size="large"   v-model="scope.row.feeName"  class="ipt"  style="text-align: center;"/> 
              </el-form-item> 
            </template> 
          </el-table-column> 
          <el-table-column :prop="formParam.feeType==0?'volume':'weight'">      
            <template #header>
            <el-dropdown trigger="click"  @command="handleCommandVolume">
              <span class="el-dropdown-link">
                {{formParam.feeType==0?'Volume':'Weight'}}
                <el-icon class="el-icon--right">
                  <arrow-down />
                </el-icon>
              </span>
              <template #dropdown>
                <el-dropdown-menu>
                  <el-dropdown-item command="0">CBM</el-dropdown-item>
                  <el-dropdown-item command="1">MT</el-dropdown-item>
                </el-dropdown-menu>
          </template>
        </el-dropdown>
        </template>
            <template #default="scope"> 
              <el-form-item v-if="formParam.feeType==0"  :prop="'details.'+scope.$index+'.volume'" :rules="detailRules.volume" required>
                <el-input-number :precision="2" v-model="scope.row.volume"  class="ipt"  style="text-align: center;"/> 
              </el-form-item> 
              <el-form-item v-else :prop="'details.'+scope.$index+'.volume'" :rules="detailRules.volume" required>
                <el-input-number :precision="2" v-model="scope.row.weight"  class="ipt"  style="text-align: center;"/> 
              </el-form-item> 
            </template> 
          </el-table-column>
          <el-table-column label="Unit" prop="unit"> 
            <template #default="scope"> 
              <el-form-item  :prop="'details.'+scope.$index+'.unit'" :rules="detailRules.unit" required>
                <el-input-number  v-model="scope.row.unit"  class="ipt"  style="text-align: center;"/> 
              </el-form-item> 
            </template> 
          </el-table-column>
          <el-table-column label="Unit Price" prop="unitPrice"> 
            <template #default="scope"> 
              <el-form-item  :prop="'details.'+scope.$index+'.unitPrice'" :rules="detailRules.unitPrice" required>
                <el-input-number :precision="2"  v-model="scope.row.unitPrice"  class="ipt"  style="text-align: center;"/> 
              </el-form-item> 
            </template> 
          </el-table-column>
          <el-table-column label="Currency" prop="currency"> 
            <template #default="scope"> 
              <el-form-item  :prop="'details.'+scope.$index+'.currency'" :rules="detailRules.currency" required>
                <el-select v-model="scope.row.currency">
                  <el-option v-for="item in currency_type"  :value="item.label" :label="item.label" :key="item.label" /> 
                </el-select>
              </el-form-item> 
            </template> 
          </el-table-column>
          <el-table-column label="Amount" prop="amount">
            <template #default="scope">
              {{ formParam.feeType == 0 ?((scope.row.volume||0) * (scope.row.unitPrice||0)).toFixed(2): ((scope.row.weight||0) * (scope.row.unitPrice||0)).toFixed(2)}}
            </template>
          </el-table-column>  
          <el-table-column label="Operation">
            <template #default="scope"> 
              <el-button size="small"  type="text" @click="addItem()" >Add</el-button>
              <el-button  size="small"  type="text"  @click="deleteItem(scope.$index)" >Delete</el-button>
            </template>   
          </el-table-column>
        </el-table>

	   <!-- <table class="mytable" border="0" cellpadding="0" cellspacing="0" width="100%">
        <tbody>
          <tr>
            <th>Item</th><th>Fee Name</th><th>Volume</th><th>Unit</th><th>Unit Price</th>
            <th>Currency</th> <th>Amount</th><th>Operation</th>
          </tr>	  
          <tr  v-if="formParam.details" v-for="detail in formParam.details"> 
            <td width="8%" style="text-align: center;">  {{detail.item}} </td>
            <td width="12%" style="text-align: center;">   
               <el-form-item  label-width="0px" prop="feeName" >
              <el-input v-model="detail.feeName" class="ipt" style="text-align: center;" />
              </el-form-item></td>
            <td width="14.2%"> 
              <el-form-item label="" label-width="0px" prop="volume" >
              <el-input-number v-model="detail.volume" class="ipt" style="text-align: center;" />
              </el-form-item>
            </td>
            <td width="14.2%">
              <el-form-item label="" label-width="0px" prop="unit" >
              <el-input type="number" v-model="detail.unit" class="ipt" @change="selectCurrency" style="text-align: center;" />
              </el-form-item>
            </td>
            <td width="14.2%">
              <el-form-item label="" label-width="0px" prop="unitPrice" >
              <el-input-number v-model="detail.unitPrice" class="ipt" @change="selectCurrency " style="text-align: center;" :precision="2"/>
              </el-form-item>
            </td>
            <td width="14.2%">
                <el-form-item label="" label-width="0px" prop="currency" >
                <el-select v-model="detail.currency">
                        <el-option v-for="item in currency_type"  @change="selectCurrency" :value="item.label" :label="item.label" :key="item.label" /> 
                </el-select>
              </el-form-item>
            </td>
            <td width="14.2%" style="text-align: center;"> 
              {{ (detail.unit * detail.unitPrice).toFixed(2) }}
            </td> 
            <td> 
              <el-button size="small"  type="text" @click="addItem()" >Add</el-button>
              <el-button  size="small"  type="text"  @click="deleteItem(scope.$index)" >Delete</el-button>
            </td>            
          </tr>
		      <tr v-else>
            <td>&nbsp;</td><td></td><td></td><td></td><td></td>
            <td></td> <td></td>
          </tr>			  
        </tbody>
	   </table>		 -->
        <el-row v-if="formParam.details">
          <el-col :span="8">
            <el-form-item  label="Total"  label-width="120px" prop="units" >		
              {{ detailsTotal.toFixed(0) }}			
            </el-form-item>
          </el-col>
          <el-col  :span="8">

          </el-col>
          <el-col :span="8">
            <el-form-item   label-width="120px" prop="sumTotal" >
			         {{ detailsSumTotal.toFixed(2) }}
            </el-form-item>
          </el-col>
        </el-row>
        <el-row v-else>
          <el-col :span="8">
            <el-form-item  label="Total"  label-width="120px" prop="units" >	0			
            </el-form-item>
          </el-col>
          <el-col  :span="8">

          </el-col>
          <el-col :span="8">
            <el-form-item   label-width="120px" prop="sumTotal" >
			        0
            </el-form-item>
          </el-col>
        </el-row>		
        <el-row>
          <el-col :span="12">
            <el-form-item label="BENEFICIARY'S NAME" label-width="180px" required>
                <el-input v-model="formParam.beneficiaryName" />
             </el-form-item>
          </el-col>
          <el-col :span="12"> 
             <el-form-item label="BENEFICIARY'S ADDRESS" label-width="220px" prop="beneficiaryAddress" required>
                <el-input v-model="formParam.beneficiaryAddress" placeholder="address" />
             </el-form-item>
          </el-col>
          </el-row>   
          <el-row> 
            <el-col :span="12">
             <el-form-item label="Account No" prop="accountNo" label-width="180px" required>
                <el-input v-model="formParam.accountNo" placeholder="accountNo" />
             </el-form-item>
            </el-col>
            <el-col :span="12">
             <el-form-item label="Bank Name" prop="bankName" label-width="180px"  required>
                <el-input v-model="formParam.bankName" placeholder="Bank Name" />
             </el-form-item>      
            </el-col>   
          </el-row>   
          <el-row> 
            <el-col :span="12">
              <el-form-item label="Bank Address" prop="bankAddress" label-width="180px" required>
                  <el-input v-model="formParam.bankAddress" placeholder="Bank Address" />
              </el-form-item>      
            </el-col>
            <el-col :span="12">
              <el-form-item label="Country" prop="country"  label-width="160px" required>
                <el-select  v-model="formParam.country"  filterable  placeholder="choose COUNTRY"   clearable >
                  <el-option
                     :key="item.countryName"
                     :label="item.countryName"
                     :value="item.countryName"
                     v-for="item in countrys">
                  </el-option>
                </el-select>  
              </el-form-item>   
            </el-col>
          </el-row>    
          <el-row>
            <el-col :span="12">
              <el-form-item label="Province" prop="province"  label-width="160px" required>
               <el-input v-model="formParam.province" placeholder="Province" />
            </el-form-item>     
            </el-col>
            <el-col :span="12">
              <el-form-item label="Swift Code" prop="swiftCode"  label-width="180px" required>
                <el-input v-model="formParam.swiftCode" placeholder="Swift Code" />
              </el-form-item>   
           </el-col> 
          </el-row>
     </el-form>
     <div class="dialog-footer"> 
      <el-button type="warning"   @click="backListHandle">Back</el-button>
      <el-button type="primary" @click="submitForm">Submit</el-button> 
    </div>
  </div> 
 </template>
 <script lang="ts" setup name="freightConfirmation">
 import { ref, onMounted, reactive, computed } from "vue";
import { ElNotification ,ElMessageBox,ElMessage } from "element-plus"; 
import { downloadFile } from "@/utils/downloadFile";
import { convertDate } from "@/utils/date"
import service from "@/utils/request";
import { useTableDrag } from '@/hooks/useHooks'
import useUserStore from '@/store/modules/user' 
let user = useUserStore().GetInfo(); 
const { tableRef } = useTableDrag();
const route = useRoute(); 
const router = useRouter();
const custForm = ref();
const dialogTitle = ref("");
const initForm = {
   id: null,
   fixtureCode: null,
   freightDate: convertDate(new Date()),
   salesId: user.id,
   clientName: null,
   mobile: null,
   contact: null,
   vesselName: null,
   voyageNo: null,
   sailedOn: null,
   pol: null,
   pod: null,
   bookingNo: null,   
   blNo: null,
   units: null,
   details: [   ],
   beneficiaryName: null,
   beneficiaryAddress: null,
   accountNo: null,
   bankName:null,
   bankAddress: null,
   country: null,
   province:null,
   swiftCode:null,
   feeType:0,
   revenue: 0
 };
 const formRef = ref(null)
 const formParam = reactive(Object.assign({}, initForm));
 const isLoading = ref(false);
 const total = ref(0);
 let countrys = ref([])
 const proxy = getCurrentInstance()?.proxy

 let vessels = reactive([] as any);
let voyages = reactive([] as any);
let pols = reactive([] as any)
let pods = reactive([] as any)
let clients = reactive([])
const selectVessel =()=>{ 
  queryParams.voyageNo = null;
  queryParams.pol = null;
  queryParams.pod = null;
  voyages = [];
  pods = [];
  pols = [];
  if(queryParams.vesselName != null && queryParams.vesselName != undefined){ 
    let item = vessels.find(n=>n.vesselName == queryParams.vesselName) 
    if(item){
      voyages = item.schedules
    } 
  } 
}

const addItem = ()=>{
  formParam.details.push({item:formParam.details.length+1, unit:null, unitPrice:null, currency:'USD'})
}

const deleteItem=(index)=>{
  if( formParam.details != null && formParam.details.length > 1){
    formParam.details.splice(index, 1);
  } 
  for(let i in formParam.details){
    formParam.details[i].item = parseInt(i)+1;
  }
}

const selectVoyage = async()=>{
  queryParams.pol = null;
  queryParams.pod = null;

   //@ts-ignore
  let item = voyages.find(n=>n.voyageNo ==queryParams.voyageNo)
  if(item){
    pods = item.pods
    pols = item.pols
  }
}
  

 const detailRules = ref({
  feeName:[{ required: true, message: "Fee Name is required" }], 
  unit:[{ required: true, message: "unit is required" }], 
  volume:[{ required: true, message: "volume is required" }], 
  currency:[{ required: true, message: "currency is required" }], 
  unitPrice:[{ required: true, message: "currency is required" }], 
 })

 const rules = ref({
   fixtureCode:[{ required: true, message: "Fixture Code is required" }],  
 });


 const noshowForm = ref(true)
 
 noshowForm.value = !route.query?.showForm 
	
 const queryParams = reactive({
   pageNum: 1,
   pageSize: 20,
   fixtureCode: null, 
   carrierCode: null,
   vesselName: null,
   voyageNo: null,
   pol: null,
   pod: null,
   clientName: null,
   orderByColumn: undefined,
   isAsc: undefined
 });
 
let blNos = reactive([])
let fixtureNotes = reactive([])

let detailsTotal= computed(()=>{
  if(formParam.details == null){
    return 0
  }
  return formParam.details.reduce((acc, item) => (acc+(item.unit * 1.0)), 0);
});

let detailsSumTotal = computed(()=>{
  if(formParam.details == null){
    return 0
  }
  if(formParam.feeType == 0){
    return formParam.details.reduce((acc, item) => (acc+(item.unitPrice?(item.volume *1.0* item.unitPrice):0)), 0);
  }else{
    return formParam.details.reduce((acc, item) => (acc+(item.unitPrice?(item.weight *1.0* item.unitPrice):0)), 0);
  }
  
});

const listData = ref([]); 
 const refreshTable = async () => {
   let result = await service.get("/shipping/freightConfirm/getTable", { params: queryParams });
   if(result){
      listData.value = result.data;
      total.value = result.total;
   }   
 };
 const resetQuery = (data) => {
    Object.assign(queryParams, data)
    listData.value = []
    total.value = 0
  }
 const selectFixture = async()=>{
  let fixtureIndex = fixtureNotes.findIndex(item => item.fixtureNo == formParam.fixtureCode)   
  formParam.clientName = fixtureNotes[fixtureIndex].clientName
  formParam.vesselName = fixtureNotes[fixtureIndex].vesselName
  formParam.voyageNo = fixtureNotes[fixtureIndex].voyageNo
  
  formParam.pol = fixtureNotes[fixtureIndex].pol
  formParam.pod = fixtureNotes[fixtureIndex].pod
  let item = vessels.find(n=>n.vesselName == queryParams.vesselName) 
  if(item){
    voyages = item.schedules    
  } 
  

  let params = {clientName: formParam.clientName}
  let result  = await service.get("/shipping/client/getInfoByName",{params:params})
  if(result && result.data){
    formParam.mobile = result.data.mobile
    formParam.contact = result.data.contact 
  }

  params ={clientName: formParam.clientName,vesselName: formParam.vesselName, voyageNo: formParam.voyageNo,pol:formParam.pol,pod:formParam.pod} 
  result = await service.post("/shipping/cargoManifest/getFinishedBook",params)
  if(result?.data){
    formParam.bookingNo = result.data.bookingNo?result.data.bookingNo:formParam.bookingNo
    formParam.blNo = result.data.blNo?result.data.blNo:formParam.blNo
    formParam.sailedOn = result.data.sailedOn?result.data.sailedOn:formParam.sailedOn
    formParam.pol = result.data.pol?result.data.pol:formParam.pol
    formParam.pod = result.data.pod?result.data.pod:formParam.pod

    formParam.units = result.data.totalUnits?result.data.totalUnits:formParam.totalUnits 
    if(formParam.details == null || formParam.details.length == 0){
      formParam.details = result.data.details
      if(result.data.details != null){
      for(let i in formParam.details){
         formParam.details[i].item = Number(i)+1
         formParam.details[i].feeName = "ocean freight"
          formParam.details[i].currency = "USD"
      }
      //detailsTotal.value= result.data.details.reduce((acc, item) => (acc+(item.unit * 1.0)), 0);
	    //detailsSumTotal.value= result.data.details.reduce((acc, item) => (acc+(item.unitPrice?(item.unit *1.0* item.unitPrice):0)), 0);
    } 
    } 
  }

  params = {carrierCode: fixtureNotes[fixtureIndex].carrierCode}
  result = await service.get("/shipping/carrier/getCarrierByCode",{params:params})
  if(result){
    let bankInfo:any = result.data.bankInfo
    if(bankInfo != null){
      formParam.beneficiaryAddress = bankInfo.beneficiaryAddress 
      formParam.beneficiaryName = bankInfo.beneficiaryName
      formParam.accountNo = bankInfo.accountNo
      formParam.country = bankInfo.country
      formParam.province = bankInfo.province
      formParam.bankName = bankInfo.bankName
      formParam.bankAddress = bankInfo.bankAddress
      formParam.swiftCode = bankInfo.swiftCode
    }    
  }
 }
const dialogFormVisible = ref(false);

 const editClickEvent = (row: any) => {
   dialogTitle.value = "Update Freight Confirm";
   dialogFormVisible.value = true;
   noshowForm.value=false
   isAdd = false;
   console.log(row)
   Object.keys(initForm).forEach((k) => (formParam[k] = row[k]));  
 };
 
 let isAdd = false;
 
 const addClickEvent = () => {
  isAdd = true;
	noshowForm.value=false
  console.log();
  Object.assign(formParam, initForm);
  router.push({ path: '/contract/freightConfirm',query:{showForm: true} }) 
 };
 
 const resetForm = () => {
   // @ts-ignore
   custForm.value.resetFields();
 };
 
 const submitForm = () => {     
    custForm.value.validate(async valid => {
      if (!valid) { 
        ElMessage.error("Verification failed! ")
        return;
      } 
      if (isLoading.value) return; 
      isLoading.value = true;
      isAdd = (formParam.id == null)

      if(formParam.details == null || formParam.details.length == 0){
        ElMessage.error("Fee Detail is required! ")
        return
      }
      formParam.revenue = 0.0;
      for(let i in formParam.details){
        if(formParam.details[i].weight != null && formParam.details[i].unitPrice != null){
          if(formParam.feeType == 0){
            formParam.details[i]['amount'] =  (formParam.details[i].volume * formParam.details[i].unitPrice).toFixed(2)
            formParam.revenue += (formParam.details[i].volume * formParam.details[i].unitPrice)
            
          }else{
            formParam.details[i]['amount'] =  (formParam.details[i].weight * formParam.details[i].unitPrice).toFixed(2)
             formParam.revenue += (formParam.details[i].weight * formParam.details[i].unitPrice)
          }          
        }  
      }
      

      await service[isAdd ? "post" : "put"]("shipping/freightConfirm", formParam);
      // @ts-ignore
      ElNotification.success({ title: "Prompt information", message: "save successful!", position: "bottom-right" });
      dialogFormVisible.value = false;
      isLoading.value = true;
      noshowForm.value=true
      refreshTable();
   });
 };
 
 const pageQuery = async e => {
   queryParams.pageNum = e.page;
   queryParams.pageSize = e.limit;
   refreshTable();
 };
 
 const search = () => {
  if([null, '', undefined].includes(queryParams.vesselName)|| [null, '', undefined].includes(queryParams.voyageNo)){
    ElMessage.warning("Please select vessel and voyage to query!") 
    return
  } 
   refreshTable();
 };

  
 const handleSortChange = async (column: any) => {
   queryParams.orderByColumn = column.prop;
   queryParams.isAsc = column.order; //动态取值排序顺序
   refreshTable();
 };
 
 const removeClickEvent = id => {
   ElMessageBox.confirm("Confirm to Remove the data？", "Confirmation Information", {
     type: "warning",
     confirmButtonText: "Confirm",
     cancelButtonText: "Cancel"
   }).then(async () => {
     await service.delete(`shipping/freightConfirm/${id}`);
     refreshTable();
     // @ts-ignore
     ElNotification.success({ title: "Prompt information", message: "Delete successfully!", position: "bottom-right" });
   });
 };
 
 const backListHandle=()=>{
  router.push({ path: '/contract/freightConfirm' }) 
  noshowForm.value=true
}
 
function formatDate() {
  let date=new Date()
  let year = date.getFullYear();
  let month = (date.getMonth() + 1).toString().padStart(2, '0');
  let day = date.getDate().toString().padStart(2, '0');
  return `${year}${month}${day}`;
}

function handleExport(row:any) {
  downloadFile("/shipping/freightConfirm/export", row, `freight_confirm_${row['fixtureCode']}_${formatDate()}.xlsx`);
}

let currency_type = reactive([])
onMounted(async () => {

  let result = await service.get("/shipping/client/list");
  if (result) {
    clients = result.data
  }
  result = await service.get("/shipping/fixtureNote/list");
  if (result) {
    fixtureNotes = result.data
  }
  service.get("/shipping/country/list").then((result:any) =>{
    countrys.value = result.data;
  }) 

  result = await service.get("/shipping/schedule/getAllSchedule");
  if (result) {
    vessels = result.data;
  } 
   const res = await proxy.useDict("currency_type");
   currency_type = res.currency_type
   refreshTable();
 });

 const handleCommandVolume=( value)=>{
  formParam.feeType=value
 }
 
 </script> 
 <style scoped lang="scss">
.el-dropdown-link {
  display: flex;
  align-items: center;
  font-size: 12px;
  line-height: 2;
}
// .query-wrapper {
//   display: flex;
//   margin: 0 15px 0 25px;
//   border-radius: 3px;
//   align-items: center;
//   height: var(--input-height);
//   font-size: var(--content-font-size);
//   line-height: var(--input-line-height);
//   width: 1200px;
// }
.add-container {
  padding-top: 30px;
  background-color: #fafafa;
  height: 100%;
}
.mytable{
   border-color: gray;
   width: 100%;
   font-size:12px;
   padding:0 10px;
}
.mytable th{
   color: var(--title-font-color);
   text-align: center;
   background-color: #ecf2fb;
   height:35px;
}
.mytable td{
   padding:4px;
   font-size:12px;
}

.dialog-footer {
margin: 60px auto 0;
width: 100%;
text-align: center;
}
.d-center {
  display: flex;
  align-items: center;
  justify-content: center;
}

input[aria-hidden=true]{
  display: none !important;
}
</style>